<?php

namespace app\common\model\Product;

use think\Model;

/**
 * 商品模型
 */
class Product extends Model
{
    //模型对应的是哪张表
    protected $table = "pre_product";

    //开启自动写入
    protected $autoWriteTimestamp = false;

    //设置字段的名字
    protected $createTime = false; //插入的时候设置的字段名

    //禁止 写入的时间字段
    protected $updateTime = false;

    //如果想要在查询的时候显示出，获取器自定义的字段
    protected $append = [
        'thumbs_cdn', //多张
        'cover_cdn', //单张
        'type', //商品类型
        'product_status', //商品状态
    ];

    //图片字段的获取器 thumbs_cdn
    public function getThumbsCdnAttr($value, $data)
    {
        //获取的是config.php 当中的cdn选项
        $cdn = config('cdn');

        // $thumbs = empty($data['thumbs']) ? [] : explode(',', $data['thumbs']);
        $thumbs = empty($data['thumbs']) ? [] : trim($data['thumbs']);

        if (empty($thumbs)) {
            return [];
        }

        //字符串替换
        // uploads/20211015/1.jpg, http://www.asks.com/uploads/20211015/1.jpg,

        $thumbs = str_replace("uploads/", $cdn . "/uploads/", $thumbs);

        //在转换为数组
        $list = explode(',', $thumbs);

        return $list;
    }

    //单张
    public function getCoverCdnAttr($value, $data)
    {
        //获取的是config.php 中的cdn选项
        $cdn = config('cdn');

        // $thumbs = empty($data['thumbs']) ? [] : explode(',', $data['thumbs']);
        $thumbs = empty($data['thumbs']) ? [] : trim($data['thumbs']);

        if (empty($thumbs)) {
            return [];
        }

        //字符串替换
        $thumbs = str_replace("uploads/", $cdn . "/uploads/", $thumbs);

        //在转换为数组
        $list = explode(',', $thumbs);

        if (count($list) > 0) {
            return $list[0];
        } else {
            return $cdn . "/static/admin/images/product.jpg";
        }
    }

    //商品类型
    public function type()
    {
        return $this->belongsTo('app\common\model\Product\Type', 'typeid', 'id', [], 'LEFT');
    }

    //商品状态
    public function getProductStatusAttr($value, $data)
    {
        $statusList = [
            1 => '新品',
            2 => '热销',
            3 => '推荐'
        ];

        return $statusList[$data['flag']];
    }

    /**
     * 1:n,把1的主键放到多里面做外键
     * 关联查询 belongTp 参数
     * 参数一:1表的模型
     * 参数二:多表的外键
     * 参数三:一表的主键
     */
}
